import React from 'react'
import {connect} from 'react-redux'
import {Button, Popover, Icon, Checkbox, Radio, Modal} from 'antd';
import ListSelector from 'components/list-selector'
import 'styles/financial-management/supplier-management/supplier-company-delivery.scss'
import menuRoute from 'routes/menuRoute'
import BasicInfo from 'components/basic-info'
import {messages} from "share/common";
import ResizeTable from 'components/resize-table'
import CustomerInfoMaintenanceService from 'containers/customer-info-maintenance/customer-info-maintenance.service'

class CustomerCompanyDelivery extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tenant: window.location.href.indexOf('tenant') !== -1,
      type: window.location.href.indexOf('tenant') !== -1 ? 'tenant' : 'company',
      loading: false,
      data: [],
      customerInfo: {},
      companyListSelector: false,  //控制公司选则弹框
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
      },
      infoList: [
        {
          type: 'input',
          id: 'customerTypeName',
          disabled: true,
          label: messages('customer-info-maintenance.key1')/*客户类型*/
        },
        {
          type: 'input',
          id: 'customerCode',
          disabled: true,
          label: messages('customer-info-maintenance.key2')/*客户代码*/
        },
        {
          type: 'input',
          id: 'customerName',
          disabled: true,
          label: messages('customer-info-maintenance.key3')/*客户名称*/
        },
        {
          type: 'switch',
          id: 'enabled',
          defaultValue: true,
          label: messages('common.column.status')
        },
      ],
      columns: [
        {
          title: messages('financial-management.key342'/*公司代码*/),
          key: "companyCode",
          dataIndex: 'companyCode',
          render: text => <span><Popover content={text}>{text ? text : "-"}</Popover></span>
        },
        {
          title: messages('financial-management.key343'/*公司名称*/),
          key: "companyName", dataIndex: 'companyName',
          render: text => <span><Popover content={text}>{text ? text : "-"}</Popover></span>
        },

        {
          title: messages('financial-management.key345'/*账套*/),
          key: "setOfBooksName",
          dataIndex: 'setOfBooksName',
          render: text => <span><Popover content={text}>{text ? text : "-"}</Popover></span>
        },
        {
          title: messages('common.status.enable'),
          key: "enabled",
          dataIndex: 'enabled',
          width: '10%',
          render: (isEnabled, record) => <Checkbox onChange={(e) => this.onChangeEnabled(e, record)} checked={record.enabled}/>
        }
      ],
    }
  }

  componentWillMount() {
    this.getCustomerDetail();
  }

  componentWillReceiveProps(nextProps){
    if(this.props.location.pathname !== nextProps.location.pathname){
      let tenant = nextProps.location.pathname.indexOf('tenant') !== -1;
      let type = tenant ? 'tenant' : 'company';
      this.setState({
        tenant,
        type,
      }, () => {
        this.getCustomerDetail();
      });
    }
  }
  //获取客户信息详情
  getCustomerDetail = () => {
    const {tenant} = this.state;
    CustomerInfoMaintenanceService.getCustomerDetail(this.props.params.id)
      .then(res => {
        if(!res.data.public){
          this.getCompanyList();
        }
        this.setState({
          customerInfo: res.data,
        })
      }
    ).catch(err => {
    })
  };

  //获取已分配公司列表
  getCompanyList = () => {
    const {pagination} = this.state;
    this.setState({loading: true});
    CustomerInfoMaintenanceService.getCompanyList(this.props.params.id).then(res => {
      this.setState({
        loading: false,
        data: res.data,
        pagination: {
          current: pagination.page + 1,
          total: Number(res.headers['x-total-count']) || 0,
          onChange: this.onChangePager,
        }
      })
      }
    ).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };


  //分页点击
  onChangePager = (pagination) => {
    let temp = this.state.pagination;
    temp.page = pagination.current-1;
    temp.current = pagination.current;
    this.setState({
      pagination: temp
    }, () => {
      this.getCompanyList();
    })
  };

  //控制是否弹出公司列表
  showListSelector = (flag) => {
    this.setState({
      companyListSelector: flag
    })
  };

  //处理公司弹框点击ok,分配公司
  handleListOk = (result) => {
    const {tenant, customerInfo} = this.state;
    if (result.result.length > 0) {
      let arr = [];
      result.result.map(item => {
        arr.push(item.id)
      });
      let params = {companyIdList: arr, customerIdList: [customerInfo.id]};
     this.assignPartCompany(params);
    }
    this.showListSelector(false)
  };

  //分配全部公司
  assignAllCompany = () => {
    const {tenant, customerInfo} = this.state;
    CustomerInfoMaintenanceService.editCustomerObject(customerInfo, tenant ? "?roleType=TENANT" : "").then(res => {
        this.getCustomerDetail();
      }
    ).catch(err => {
    })
  };

  //分配部分公司
  assignPartCompany = (params) => {
    CustomerInfoMaintenanceService.assignPartCompany(params).then(res => {
        this.getCompanyList();
      }
    ).catch(err => {
    })
  };

  onRadioChange = (e) => {
    const {customerInfo} = this.state;
    if(e.target.value){
      Modal.info({
        title: messages('customer-info-maintenance.key4')/*切换全部公司后，将清空当前分配公司信息。*/,
        onOk: () => {
          customerInfo.public = e.target.value;
          this.setState({
            customerInfo,
          },() => {
            this.assignAllCompany();
          });
          },
      })
    }else {
      customerInfo.public = e.target.value;
      this.setState({
        customerInfo,
      });
    }
  };

  //改变启用状态
  onChangeEnabled = (e, record) => {
    const {tenant} = this.state;
    this.setState({loading: true});
    let params = {
      companyId: record.companyId,
      customerId: this.props.params.id,
      enabled: e.target.checked,
    };
    CustomerInfoMaintenanceService.enableCompany(params)
      .then(response => {
        this.getCompanyList()
      })
  };

  //返回
  handleBack = () => {
    const {type} = this.state;
    this.context.router.push(menuRoute.getRouteItem(`customer-${type}-maintenance`, 'key').url)
  };

  render() {
    const {loading, data, columns, pagination, companyListSelector, customerInfo, infoList} = this.state;
    return (
      <div className="supplier-company-delivery">
        <BasicInfo
          infoList={infoList}
          infoData={customerInfo}
          isHideEditBtn={true}/>
          <br/>
          <Radio.Group onChange={this.onRadioChange} value={customerInfo.public}>
            <Radio value={true}>{messages('customer-info-maintenance.key5')/*全部公司*/}</Radio>
            <Radio value={false}>{messages('customer-info-maintenance.key6')/*部分公司*/}</Radio>
          </Radio.Group>
          <br/>
        {
          !customerInfo.public &&
            <div>
              <div className="table-header">
                <div className="table-header-title">
                  {messages('common.total', {total: `${pagination.total}`})}</div>
                {/*共搜索到*条数据*/}
                <div className="table-header-buttons">
                  {this.checkNewAuth() && <Button type="primary" onClick={() => this.showListSelector(true)}>
                    {messages('financial-management.key346'/*批量分配公司*/)}</Button>}
                </div>
              </div>
              <ResizeTable
                loading={loading}
                dataSource={data}
                pagination={pagination}
                columns={columns}
                onChange={this.onChangePager}
                bordered
                size="middle"
              />
            </div>
        }
        <a style={{fontSize: '14px', paddingBottom: '20px'}}
           onClick={this.handleBack}>
          <br/>
          <Icon type="rollback" style={{marginRight: '5px'}}/>{messages('common.back')}</a>
        <ListSelector type="vendor_company"
                      visible={companyListSelector}
                      onOk={this.handleListOk}
                      extraParams={{tenantId: this.props.company.tenantId, infoId: customerInfo.id}}
                      onCancel={() => this.showListSelector(false)}/>
      </div>)
  }
}

CustomerCompanyDelivery.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    main: state.main
  }
}

export default connect(mapStateToProps)(CustomerCompanyDelivery);
